import express from 'express';
import http from 'http';
import { connect, NatsConnection } from 'nats';
import { Server } from 'socket.io';

const connectNATS = async (): Promise<NatsConnection> => {
    const nc = await connect({
      servers: 'nats://your-server:4222',
      timeout: 5000,
    });
  
    console.log(`Connected to ${nc.getServer()}`);
    return nc;
  };
  
  // 优雅关闭
  process.on('SIGTERM', () => nc.close());
  process.on('SIGINT', () => nc.close());

// 创建 Express 应用
const app = express();
// 创建 HTTP 服务器
const server = http.createServer(app);
// 创建 Socket.IO 服务器
const io = new Server(server);

// 设置静态文件目录（可选）
app.use(express.static('public'));

// Socket.IO 连接事件
io.on('connection', (socket) => {
  console.log('A user connected:', socket.id);

  // 监听客户端消息
  socket.on('message', (msg) => {
    console.log('Message received:', msg);
    // 广播消息给所有连接的客户端
    io.emit('message', msg);
  });

  // 断开连接事件
  socket.on('disconnect', () => {
    console.log('User disconnected:', socket.id);
  });
});

// 设置服务器端口
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});




// 发布消息
const publishEvent = async (subject: string, data: object) => {
    const payload = JSON.stringify(data);
    nc.publish(subject, Buffer.from(payload));
  };
  
  // 订阅消息
  const subscribeEvents = async (subject: string) => {
    const sub = nc.subscribe(subject);
    
    try {
      for await (const msg of sub) {
        const data = JSON.parse(Buffer.from(msg.data).toString());
        console.log(`[${msg.subject}] Received:`, data);
      }
    } catch (err) {
      console.error('Subscription error:', err);
    } finally {
      sub.unsubscribe();
    }
  };



  const requestData = async (subject: string, payload: object) => {
    try {
      const response = await nc.request(
        subject,
        Buffer.from(JSON.stringify(payload)),
        { timeout: 3000 }
      );
      
      return JSON.parse(Buffer.from(response.data).toString());
    } catch (err) {
      throw new Error(`Request failed: ${err.message}`);
    }
  };


  /*
 请求数据
  try {
  const res = await nc.request("sensor.read", sc.encode("temp"), { timeout: 2000 });
  if (res.headers?.get("status") !== "200") {
    throw new Error("服务端异常");
  }
  handleData(jc.decode(res.data));
} catch (err) {
  if (err.code === "TIMEOUT") {
    retryRequest();
  } else {
    logError(err);
  }
}
  */

  // 事件监听
nc.addEventListener('error', (err) => {
    console.error('NATS connection error:', err);
  });
  
  nc.addEventListener('connect', () => {
    console.log('Connection reestablished');
  });


  // 健康检查端点 
app.get('/health', (req, res) => {
  res.status(nc.isClosed() ? 503 : 200).json({
    nats: nc.isClosed() ? 'down' : 'up'
  });
});




/*二进制编码
const sc = StringCodec(); // 内置高效编码器
nc.publish('event', sc.encode(JSON.stringify(data)));
*/